package fr.snac.notification;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.WallpaperManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.tumblr.jumblr.JumblrClient;
import com.tumblr.jumblr.types.Photo;
import com.tumblr.jumblr.types.PhotoPost;
import com.tumblr.jumblr.types.PhotoSize;
import com.tumblr.jumblr.types.Post;

import fr.snac.utils.Constants;
import fr.snac.utils.DateUtil;
import fr.snac.utils.PhotoUtil;
import fr.snac.utils.TumblrClient;

public class AsyncCheck extends AsyncTask<Calendar, Void, IOException>{
	
	volatile CheckTimerTask task;
	Bitmap image;
	Calendar date;
	Calendar today;
	Context context;
	JumblrClient client;
	PhotoSize photoSize;
	SharedPreferences settings;
	
	public AsyncCheck(CheckTimerTask task, Context context){
		this.task = task;
		this.context = context;
	}

	@Override
	protected IOException doInBackground(Calendar... params) {
		
		today = params[0];
		
		ConnectivityManager manager = (ConnectivityManager)task.service.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo network = manager.getActiveNetworkInfo();
		
		if (network.isConnected() && network.isAvailable()){
			client = TumblrClient.initializeClient();
			
			Map<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("type", "photo");
			queryParams.put("limit", 50);
			
			List<Post> posts = client.blogPosts(Constants.BLOG_ADDRESS, queryParams);
			
			if (posts.size() > 0){
				Post p = posts.get(0);
				PhotoPost pp = (PhotoPost)p;	
				
				pp = (PhotoPost)p;
				List<Photo> photos = pp.getPhotos();
				Photo photo = photos.get(0);
				List<PhotoSize> sizes = photo.getSizes();

				DisplayMetrics metrics = new DisplayMetrics();
				WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
				windowManager.getDefaultDisplay().getMetrics(metrics);				

				photoSize = PhotoUtil.getMoreAdaptedPhoto(sizes, metrics);
				date = DateUtil.getCalendarDate(DateUtil.getUSDate(pp.getDateGMT()));
			}
			
			
			URL url;
			try {
				url = new URL(photoSize.getUrl());
				InputStream is = url.openConnection().getInputStream();
				image = BitmapFactory.decodeStream(is);

				is.close();
			}catch (IOException e) {
				return e;
			}
			
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(IOException result){
		
		boolean notificationDisplayed;
		CheckTimerTask task = this.task;
		task.asyncTask = null;
		settings = context.getSharedPreferences(Constants.SETTINGS_PREFERENCES, 0);
		notificationDisplayed = settings.getBoolean(Constants.NOTIFICATION_DISPLAYED, false);
		
		if (DateUtil.isSameDay(today, date)){
			task.service.buildNotification();

			if (image != null && photoSize != null){
				if (settings.getBoolean(Constants.SETTINGS_WALLPAPER_CHANGE_ALLOWED, false)){
					String orientation = PhotoUtil.getPhotoOrientation(photoSize);				
					boolean landscape = settings.getBoolean(Constants.SETTINGS_WALLPAPER_LANDSCAPE_ALLOWED, false);
					boolean portrait = settings.getBoolean(Constants.SETTINGS_WALLPAPER_PORTRAIT_ALLOWED, false);
					boolean setWallpaper = false;

					if (landscape  && orientation.equals(Constants.PHOTO_ORIENTATION_LANDSCAPE)){
						setWallpaper = true;
						Log.d("ASYNCCHECK", "wallpaper landscape ok");
					}else if (portrait && orientation.equals(Constants.PHOTO_ORIENTATION_PORTRAIT)){
						setWallpaper = true;
						Log.d("ASYNCCHECK", "wallpaper portrait ok");
					}

					if (setWallpaper && !notificationDisplayed){
						WallpaperManager manager = WallpaperManager.getInstance(context);
						try {
							manager.setBitmap(image);
							SharedPreferences.Editor editor = settings.edit();
							editor.putBoolean(Constants.NOTIFICATION_DISPLAYED, true);
							editor.commit();
						} catch (IOException e) {
							Log.e("ASYNCCHECK ERROR", "wallpaper marche pas");
						}
					}
				}
			}
		}
		
		if (result != null){
			//do Nothing
		}
	}

}
